import qs from 'querystring'
import { http } from '@/utils/axios'
import { getCurWebsite } from '@/views/common'

export const scriptText = `
  <script>
  const style = document.createElement('style');
  style.innerText = 'a{color:#333}table{width:100%;background-color:#f2f2f2;border-collapse:collapse}thead tr th{background-color:#7a7a7a;padding:10px 4px;color:#fff}table,table tr th,table tr td{border:1px solid #999}.thead-row2 th{background-color:#ffe18a;color:#626262}tr{border-bottom:1px solid #999}tr td{background-color:#f2f2f2;padding:10px 4px;color:#333;text-align:right;min-width:70px}a:-webkit-any-link{text-decoration:none}'
  document.querySelector('head').appendChild(style)
  </script>
`

export default {
  methods: {
    getCcItemData (item, index) {
      this.loading = true
      this.$set(this.accountList[index], 'statusText', '请求中...')
      this._getCcItemData(item)
        .then(res => {
          console.log(res)
          if (res) {
            let result = ''
            res.forEach(obj => {
              if (obj && obj.name && obj.data) {
                result += `
                  <h3>${obj.name}</h3>
                  ${obj.data}
                `
              }
            })
            let { name } = item
            if (this.startDate && this.endDate) {
              name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
            }
            const tplData = result
            this.sendToMainProcess(name + '.html', tplData + scriptText)
          }
          this.$set(this.accountList[index], 'statusText', '请求成功')
        })
        .catch(e => {
          this.$set(this.accountList[index], 'statusText', e || '请求失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getAllCcItemData (reGetList) {
      this.loading = true
      const list = reGetList || this.accountList
      let tempData = []
      let index = 0
      let { name } = list[0]
      const { startDate, endDate } = this
      if (startDate && endDate) {
        name = startDate.substring(5) + '-' + endDate.substring(5) + '——' + name
      }
      // const resultList = []
      const callback = () => {
        if (this.waitExportList.length === 0) {
          return this.$message.info('请求数据为空')
        }
        const result = this.waitExportList.map(obj => {
          if (obj && obj.name && obj.data) {
            return `
                <h3>${obj.name}</h3>
                ${obj.data}
              `
          }
          return <span>null</span>
        })
        const tplData = result.join('')
        this.sendToMainProcess(name + '.html', tplData + scriptText)
        console.log('end')
      }
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getCcItemData(item)
          .then(data => {
            if (data) {
              tempData[i] = [...data]
            }
            this.$set(this.accountList[itemIndex], 'statusText', '请求成功')
          })
          .catch(e => {
            console.error(e)
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', e && typeof e === 'string' ? e : '请求失败')
          })
          .finally(() => {
            index = index + 1
            if (index === list.length) {
              console.log(tempData)
              tempData = tempData.filter(e => e)
              tempData.forEach(item => {
                this.waitExportList.push(...item)
                // resultList.push(...item)
              })
              this.loading = false
              // callback()
              this.checkExistErrorList(() => callback())
            }
          })
      }
    },
    _getCcItemData (item) {
      return new Promise((resolve, reject) => {
        // eslint-disable-next-line no-unused-vars
        const { name, psw, code } = item
        const children = this.getChilren(item.children)
        const { startDate, endDate } = this
        const baseUrl = getCurWebsite()
        const url = baseUrl + '/cc/gen'
        // eslint-disable-next-line eqeqeq
        let data
        if (children && children.length) {
          data = qs.stringify({
            username: name,
            pwd: psw,
            // safecode: code,
            date_start: startDate,
            date_end: endDate,
            children: children && children.length ? JSON.stringify(children) : ''
          })
        } else {
          data = qs.stringify({
            username: name,
            pwd: psw,
            // safecode: code,
            date_start: startDate,
            date_end: endDate
          })
        }
        http({
          method: 'post',
          url,
          withCredentials: false,
          data
        }).then(res => {
          if (this.checkSuccess(res)) {
            resolve(res.data.data)
          } else {
            reject(res && res.data && res.data.message)
          }
        }).catch(e => {
          console.error('Report Error: ', e)
          reject(e)
        })
      })
    }
  }
}
